package com.ltmonitor.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ltmonitor.dao.ITerminalDao;
import com.ltmonitor.dao.IVehicleDataDao;
import com.ltmonitor.entity.Terminal;
import com.ltmonitor.entity.VehicleData;
import com.ltmonitor.service.ITerminalService;

@Service("terminalService")
public class TerminalService extends BaseService<Long, Terminal> implements ITerminalService {

	@Autowired
	private ITerminalDao TerminalDao;

	@Autowired
	private IVehicleDataDao vehicleDataDao;
	
	@Override
	public boolean deleteFakeById(Long terminalId)
	{
		String hql = "from VehicleData where termId = ?";
		VehicleData vd = (VehicleData) this.vehicleDataDao.find(hql,
				terminalId);
		if (vd != null) {
			vd.setTermId(0);
			this.vehicleDataDao.saveOrUpdate(vd);//与车辆解除绑定
		}
		return TerminalDao.deleteFakeById(terminalId);
	}

	@Override
	public Terminal saveOrUpdate(Terminal t)
	{
		
		if(Terminal.STATE_UNINSTALL.equals(t.getState()) && t.getEntityId() > 0)
		{
			String hql = "from VehicleData where termId = ?";
			VehicleData vd = (VehicleData) this.vehicleDataDao.find(hql,
					t.getEntityId());
			if (vd != null) {
				vd.setTermId(0);
				this.vehicleDataDao.saveOrUpdate(vd);//与车辆解除绑定
			}
		}
		return TerminalDao.saveOrUpdate(t);		
	}
	

	/**
	 * 根据终端的7位唯一编号，获取实体类数据
	 * 
	 * @param terminalNo
	 * @return
	 */
	public Terminal getTerminalByTermNo(String terminalNo) {
		String hql = "from Terminal where termNo = ? and deleted = ?";
		return  this.find(hql, new Object[] { terminalNo, false });
	}
	
	
	/**
	 * 保存终端
	 * 
	 * @param t
	 * @throws Exception
	 */
	public Terminal saveOrUpdateTerminal(Terminal t) throws Exception {
		String hsql = "from Terminal where termNo = ? and entityId <> ? and deleted = ? ";
		Terminal otherVd = (Terminal) this.find(hsql,
				new Object[] { t.getTermNo(), t.getEntityId(), false });
		if (otherVd != null) {
			String msg = "终端ID重复,无法保存!";
			throw new Exception(msg);
		}
		TerminalDao.saveOrUpdate(t);
		return t;
	}
	

}
